package com.lktx.bbfactory.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lktx.bbfactory.common.CommonPage;
import com.lktx.bbfactory.common.exception.BizAsserts;
import com.lktx.bbfactory.common.exception.BusinessException;
import com.lktx.bbfactory.entiy.User;
import com.lktx.bbfactory.mapper.userMapper;
import com.lktx.bbfactory.service.userService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<userMapper, User> implements userService {

    /**
     * 分页查询用户
     */
    @Override
    public CommonPage<User> pageUser(int pageNum, int pageSize, String username, String name) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (username != null && !username.trim().isEmpty()) {
            wrapper.like(User::getUsername, username);
            wrapper.or().like(User::getName, username);
        }
        Page<User> userPage = this.page(page, wrapper);
        return CommonPage.restPage(userPage);
    }

    /**
     * 用户登录
     */
    @Override
    public String login(String username, String password) {
        // 查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);

        User user = this.getOne(wrapper);

        // 用户不存在
        BizAsserts.notNull(user, "用户不存在");

        // 校验密码（示例为明文对比，真实场景应加密存储 + BCryptPasswordEncoder）
        if (!user.getPassword().equals(password)) {
            throw new BusinessException("密码错误");
        }

        // 校验状态
        if (user.getStatus() != 1) {
            throw new BusinessException("账号被禁用");
        }

        // 生成 token（这里用 uuid 简单示例，真实项目用 JWT）
        // token 可以放缓存 (如 Redis) 记录登录态
        return UUID.randomUUID().toString();
    }

    @Override
    public void addUser(User user) {
        // 校验用户名唯一
        boolean existsUsername = this.lambdaQuery()
                .eq(User::getUsername, user.getUsername())
                .exists();
        BizAsserts.isTrue(!existsUsername, "用户名已存在");
        // 校验名称唯一
        boolean existsName = this.lambdaQuery()
                .eq(User::getName, user.getName())
                .exists();
        BizAsserts.isTrue(!existsName, "名称已存在");
        // 设置默认状态（如启用）
        user.setStatus(1L);
        this.save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user) {
        // 1. 必须有用户ID
        BizAsserts.notNull(user.getId(), "用户ID不能为空");
        // 2. 校验用户名唯一性（排除自己）
        long countUsername = this.count(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername())
                .ne(User::getId, user.getId()));
        if (countUsername > 0) {
            throw new BusinessException("用户名已存在");
        }
        // 3. 校验名称唯一性（排除自己）
        long countName = this.count(new LambdaQueryWrapper<User>()
                .eq(User::getName, user.getName())
                .ne(User::getId, user.getId()));
        if (countName > 0) {
            throw new BusinessException("名称已存在");
        }
        // 4. 更新
        this.updateById(user);
    }

    @Override
    public void deleteUser(Long userId) {
        User user = this.getById(userId);
        if (user == null) {
            BizAsserts.fail("用户不存在");
        }
        if ("admin".equalsIgnoreCase(user.getUsername())) {
            BizAsserts.fail("管理员账号不允许删除");
        }
        this.removeById(userId);
    }



}